require 'RMagick'
require 'rubygems'
require 'exifr'

class AdminController < ApplicationController
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @post_pages, @posts = paginate :posts, :per_page => 10
  end

  def show
    @post = Post.find(params[:id])
  end

  def new
    @post = Post.new
    @photo = Photo.new
  end

  def create
    filename = params[:photo][:uploaded_photo].original_filename.to_s
    
    # We need to ensure the filename is unique here.
    originial_filename = filename
    counter = 1
    while File.exists?("#{RAILS_ROOT}/public/photos/#{filename}") do
      filename = "#{counter}-" + originial_filename
      counter += 1
    end
    
    # Write out the image
    File.open("#{RAILS_ROOT}/public/photos/#{filename}", "wb") do |f| 
      f.write(params[:photo][:uploaded_photo].read)
    end
    
    # Create a thumbnail of that image
    img = Magick::Image.read("#{RAILS_ROOT}/public/photos/#{filename}").first
    # MAKE THIS BETTER
    # It should limit thumbnail size to a certain px.
    thumb = img.scale(0.25)
    thumb.write "#{RAILS_ROOT}/public/thumbnails/#{filename}"
    
    # Get the EXIF Data
    img = EXIFR::JPEG.new("#{RAILS_ROOT}/public/photos/#{filename}")
    params[:photo][:shutter_speed] = img.exposure_time.to_f
    params[:photo][:aperture] = img.aperture_value.to_f
    params[:photo][:camera] = img.model.to_s
    params[:photo][:data_taken] = img.date_time.to_s
    params[:photo][:iso] = img.iso_speed_ratings.to_i
    
    # Set up our photo object
    params[:photo][:image_url] = "/photos/#{filename}"
    params[:photo][:thumbnail_url] = "/thumbnails/#{filename}"
    params[:photo].delete :uploaded_photo
    
    photo = Photo.new(params[:photo])
    
    # Create the post
    params[:post][:post_date] = Time.now.to_s
    post = Post.new(params[:post])
    post.add_photos(photo)
    
    #save stuff
    created_post = post.save
        
    if created_post
      flash[:notice] = 'New post was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @post = Post.find(params[:id])
    @photos = @post.photos
  end

  def update
    @post = Post.find(params[:id])
    if @post.update_attributes(params[:post])
      flash[:notice] = 'Post was successfully updated.'
      redirect_to :action => 'show', :id => @post
    else
      render :action => 'edit'
    end
  end

  def destroy
    Post.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end
